﻿using System;
using System.Drawing;
using System.IO;

namespace MyConsoleApp.Code
{
    public class ImageHelper
    {
        //将图片以二进制流
        public static byte[] SaveImage(String path)
        {
            byte[] imgBytesIn = null;
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) //将图片以文件流的形式进行保存
            {
                using (BinaryReader br = new BinaryReader(fs))
                {
                    imgBytesIn = br.ReadBytes((int)fs.Length);  //将流读入到字节数组中
                }
            }

            return imgBytesIn;
        }

        //二进制转换图片格式
        public static Image Byte4Image(byte[] imgBytes)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(imgBytes))
                {
                    return Image.FromStream(ms);
                }
            }
            catch
            {
                return null;
            }
        }

        //系统缩略图
        public static Image GetThumbnailImage(byte[] imgBytes, int width, int height)
        {
            try
            {
                Image result = Byte4Image(imgBytes);
                if (result == null)
                {
                    return null;
                }
                else
                {
                    return result.GetThumbnailImage(width, height, null, new System.IntPtr());
                }
            }
            catch
            {
                return null;
            }
        }
    }
}